package com.thread.syn;

//不安全的取钱
//两个人,账户
public class UnsafeBank {
    public static void main(String[] args) {
        Acount acount = new Acount(100,"共同财产");
        Drawing you = new Drawing(acount, 50);
        Drawing wife = new Drawing(acount, 100);
        new Thread(you,"你").start();
        new Thread(wife,"你老婆").start();


    }
}

//账户
class Acount{
    int money;//余额
    String name;//卡名

    public Acount(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//取钱:模拟取款
class Drawing implements Runnable{
    Acount acount;//账户
    //取了多少
    int drawingMoney;
    //还剩多少
    int nowMoney=0;
    //取钱的人
    String name;

    public Drawing(Acount acount, int drawingMoney) {
        this.acount = acount;
        this.drawingMoney = drawingMoney;
    }

    //synchronized 默认锁的是this,取钱流程没有受到干扰 所以这里需要锁定共同资源acount(用同步块)
    @Override
    public  void run() {
        synchronized (acount){
                //判断账户是否还有钱
                if (acount.money-drawingMoney<0){
                    System.out.println(Thread.currentThread().getName()+":钱不够,取不了");
                    return;
                }
                //放大问题的发生性
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //账户余额 = 余额-取得钱
                acount.money = acount.money-drawingMoney;
                //手上得钱
                nowMoney = nowMoney+drawingMoney;
                System.out.println(Thread.currentThread().getName()+"取走了"+drawingMoney);
                System.out.println(acount.name+"账户余额为:"+acount.money);
                System.out.println(Thread.currentThread().getName()+"手里得钱:"+nowMoney);
            }
    }

}


